/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.muni.fi.pb168.eis_web;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.Writer;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import java.io.File;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name = "QRServlet", urlPatterns =
{
    "/qr"
})
public class QRServlet extends HttpServlet {
    private String url;
    private String id;
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");

        id = request.getParameter("id");
        if(id==null)
        {
            //error
        }
        url = request.getServerName() + "/EIS_web/view?id=" + id;


        // get a byte matrix for the data
        BitMatrix matrix = createMatrix();
        System.out.println(request.getRealPath(request.getServletPath()));

        String filePath = request.getRealPath(request.getServletPath())+ "//..//public//img//qr//" + id + ".png";

        createFile(filePath, matrix);

        //response.sendRedirect("/EIS_web");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        id = request.getParameter("id");
        response.sendRedirect("/qr?id="+id);
    }

    /**
     * Generating QR code matrix by high weight and artwork url
     * @return qr code matrix
     */
    private BitMatrix createMatrix()
    {
        BitMatrix matrix = null;
        int h = 300;
        int w = 300;
        Writer writer = new QRCodeWriter();
        try {
            matrix = writer.encode(url,BarcodeFormat.QR_CODE, w, h);
        } catch (WriterException e) {
            System.out.println(e.getMessage());
        }

        return matrix;
    }

    /**
     * Creating qr code image.
     * @param filePath path of created image
     * @param matrix qr code matrix
     */
    private void createFile(String filePath, BitMatrix matrix)
    {
        File file = new File(filePath);
        if(file.exists()) return ;
        try {
            MatrixToImageWriter.writeToFile(matrix, "PNG", file);
            System.out.println("printing to " + file.getAbsolutePath());
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }

}

